package com.howie.hmvc.paramparse;

import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;

import com.howie.hmvc.annotations.Valid;
import com.howie.hmvc.exception.ArguErrorException;
import com.howie.hmvc.request.MultipartRequest;

public class ParamFiles extends AbsParamParse {

	private boolean isValid;
	private boolean required;
	private double minLength;
	private double maxLength;
	private String[] allowType;
	
	@Override
	public void init(Annotation[] an) throws Exception {
		Valid valid = getValid(an);
		if(valid != null){
			isValid = true;
			required = valid.required();
			minLength = valid.minLength();
			maxLength = valid.maxLength();
			allowType = valid.allowType();
		}
	}
	
	@Override
	public Object getParamter(HttpServletRequest request,HttpServletResponse response)throws Exception{
		MultipartRequest mpReq = (MultipartRequest)request;
		FileItem[] values = mpReq.getFiles(name);
		if(values == null){
			if(required){
				throw new ArguErrorException(name,"required",null);
			}
		}else if(isValid){
			for(FileItem val : values){
				if(val == null){
					if(required){
						throw new ArguErrorException(name,"required",null);
					}
				}else{
					if(val.getSize() < minLength){
						throw new ArguErrorException(name,"minLength",minLength);
					}
					if(val.getSize() > maxLength){
						throw new ArguErrorException(name,"maxLength",maxLength);
					}
					if(allowType.length > 0){
						String fileName = val.getName().toLowerCase();
						boolean allow = false;
						for(String type : allowType){
							if(fileName.endsWith("."+type.toLowerCase())){
								allow = true;
								break;
							}
						}
						if(!allow){
							throw new ArguErrorException(name,"allowType",StringUtils.join(allowType,","));
						}
					}
				}
			}
		}
		return values;
	}
	
}
